package main

import (
	"context"
	"github.com/go-kit/kit/endpoint"

	"github.com/go-kit/kit/log"
	"github.com/go-kit/kit/sd/zk"
	grpc_transport "github.com/go-kit/kit/transport/grpc"
	"google.golang.org/grpc"
	"kitc/pub"
	"net"
	"os"
)

type BookServer struct {
bookListHandler grpc_transport.Handler
bookInfoHandler grpc_transport.Handler
}

//通过grpc调用GetBookInfo时,GetBookInfo只做数据透传, 调用BookServer中对应Handler.ServeGRPC转交给go-kit处理
func (s *BookServer) GetBookInfo(ctx context.Context, in *pub.BookInfoParams) (*pub.BookInfo, error) {
	_, rsp, err := s.bookInfoHandler.ServeGRPC(ctx, in)
	if err != nil {
		return nil, err
	}
	return rsp.(*pub.BookInfo), err
}

//通过grpc调用GetBookList时,GetBookList只做数据透传, 调用BookServer中对应Handler.ServeGRPC转交给go-kit处理
func (s *BookServer) GetBookList(ctx context.Context, in *pub.BookListParams) (*pub.BookList, error) {
	_, rsp, err := s.bookListHandler.ServeGRPC(ctx, in)
	if err != nil {
		return nil, err
	}
	return rsp.(*pub.BookList), err
}

//创建bookList的EndPoint
func makeGetBookListEndpoint() endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		//请求列表时返回 书籍列表
		bl := new(pub.BookList)
		bl.BookList = append(bl.BookList, &pub.BookInfo{BookId: 1, BookName: "Go入门到精通"})
		bl.BookList = append(bl.BookList, &pub.BookInfo{BookId: 2, BookName: "go-kit入门到精通"})
		bl.BookList = append(bl.BookList, &pub.BookInfo{BookId: 2, BookName: "go-micro入门到精通"})
		return bl, nil
	}
}

//创建bookInfo的EndPoint
func makeGetBookInfoEndpoint() endpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (interface{}, error) {
		//请求详情时返回 书籍信息
		req := request.(*pub.BookInfoParams)
		b := new(pub.BookInfo)
		b.BookId = req.BookId
		b.BookName = "Go与微服务"
		return b, nil
	}
}

func decodeRequest(_ context.Context, req interface{}) (interface{}, error) {
	return req, nil
}

func encodeResponse(_ context.Context, req interface{}) (interface{}, error) {
	return req, nil
}

func main() {

	l:=log.NewLogfmtLogger(os.Stdout)


	c,_ := zk.NewClient([]string{"192.168.10.144:2181"},l)

	sv :=&zk.Service  {
		Path :"/bsvr/", // discovery namespace, example: /myorganization/myplatform/
		Name :"bsvr1",
		Data :[]byte("127.0.0.1:"+os.Args[1]),
	}
	reg := zk.NewRegistrar(c,*sv,l)
	reg.Register()


	//包装BookServer

	bookServer := new(BookServer)


	//创建bookList的Handler
	bookListHandler := grpc_transport.NewServer(
		makeGetBookListEndpoint(),
		decodeRequest,
		encodeResponse,
	)
	//bookServer 增加 go-kit流程的 bookList处理逻辑
	bookServer.bookListHandler = bookListHandler

	//创建bookInfo的Handler
	bookInfoHandler := grpc_transport.NewServer(
		makeGetBookInfoEndpoint(),
		decodeRequest,
		encodeResponse,
	)
	//bookServer 增加 go-kit流程的 bookInfo处理逻辑
	bookServer.bookInfoHandler = bookInfoHandler

	//启动grpc服务
	serviceAddress := ":"+os.Args[1]
	ls, _ := net.Listen("tcp", serviceAddress)
	gs := grpc.NewServer()
	pub.RegisterBookServiceServer(gs, bookServer)
	gs.Serve(ls)
}


